<?php
// 积分商城
namespace app\shop\controller;

use think\Db;
use think\Request;
use think\Session;
use think\Controller;
use app\shop\model\Config;
use app\shop\model\Member as MemberModel;
use app\shop\model\MemberSign as MemberSignModel;
use app\shop\model\LotteryCode as LotteryCodeModel;
use app\shop\model\IntegralGoods as IntegralGoodsModel;

class IntegralGoods extends Controller
{


    // 前置方法
    protected $beforeActionList = [
        'checkLogin' => ['index']
    ];

    /**
     * 积分中心
     */
    public function index()
    {
        // 获取会员ID
        $userId = session('member_id');

        // 会员积分
        $integral = (new MemberModel())->where(['id' => $userId])->field('integral,id')->find();

        // 获取参数
        $inquire = Request::instance()->param();
        $sort = ['sort' => 'desc', 'id' => 'desc'];
        if (!empty($inquire['orderId'])) $sort = [$inquire['orderId'] => 'desc'];

        $integralGoods = (new IntegralGoodsModel())->order($sort)->paginate(20, false, ['query' => $inquire]);

        // 判断是否签到
        $checkSign = self::checkSign($userId);


        return $this->fetch('', [
            'mate_head'      => '积分商城',
            'integral_goods' => $integralGoods,
            'integral'       => $integral,
            'check_sign'     => $checkSign,
        ]);
    }


    /**
     * 会员签到
     */
    public function member_sign()
    {
        // 获取会员ID
        $memberId = session('member_id');
        if (Request::instance()->isPost()) {
            // 每天签到获取的积分数
            $web_sign = (int)Config::where('varname', 'web_sign')->value('varvalue');

            // 判断是否签到
            $find =  Db::name('member_sign')->where(['member_id' => $memberId, 'sign_time' => date('Y-m-d')])->find();

            if ($find) {
                return ['code' => 400,'message'=>'你已签到！'];
            }

            // 启动事务
            Db::startTrans();
            try {
                // 昨天是否签到 签到获得积分
                $ini = [
                    'member_id' => Session::get('member_id'),
                    'sign_time' =>  $a = date("Y-m-d",strtotime("-1 day")),
                ];
                $find = Db::name('member_sign')->where($ini)->find();
                if (empty($find)) {
                    $sign_pre = 1;
                    // 添加记录
                    Db::name('member_sign')->insert(['member_id' => Session::get('member_id'), 'sign_time' => date('Y-m-d'),'sign'=>$sign_pre]);
                    // 增加积分
                    Db::name('member')->where(['id' => Session::get('member_id')])->setInc('integral', $sign_pre);
                    //增加获取积分记录
                    Db::name('integralRecord')->insert(['member_id' => Session::get('member_id'), 'type_id' => 1, 'type' => '签到', 'integral' => $sign_pre, 'title' => '签到', 'create_time' => time()]);
                }else{
                    if ($find['sign'] == 64) {
                        $sign_pre = 1;
                        // 添加记录
                        Db::name('member_sign')->insert(['member_id' => Session::get('member_id'), 'sign_time' => date('Y-m-d'),'sign'=>$sign_pre]);
                        // 增加积分
                        Db::name('member')->where(['id' => Session::get('member_id')])->setInc('integral', $sign_pre);
                        //增加获取积分记录
                        Db::name('integralRecord')->insert(['member_id' => Session::get('member_id'), 'type_id' => 1, 'type' => '签到', 'integral' => $sign_pre, 'title' => '签到', 'create_time' => time()]);
                    }else{
                        $sign_pre = $find['sign']*2;

                        // 添加记录
                        Db::name('member_sign')->insert(['member_id' => Session::get('member_id'), 'sign_time' => date('Y-m-d'),'sign'=>$sign_pre]);
                        // 增加积分
                        Db::name('member')->where(['id' => Session::get('member_id')])->setInc('integral', $sign_pre);
                        //增加获取积分记录
                        Db::name('integralRecord')->insert(['member_id' => Session::get('member_id'), 'type_id' => 1, 'type' => '签到', 'integral' => $sign_pre, 'title' => '签到', 'create_time' => time()]);
                    }
                }

                // 提交事务
                Db::commit();

                return ['code' => 200, 'sign' => $web_sign];

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                return ['code' => 400,'message'=>'网络繁忙，请稍后再试'];
            }
        }

    }


    public function integral_code()
    {
        Db::startTrans();

        try {
            // 生成抽奖码
            $model = new LotteryCodeModel();

            //获取最后一条信息
            $find = $model->max('lottery_code');

            if ($find) {
                $lottery_code = (int)$find + 1;
            } else {
                $lottery_code = 1000001;
            }

            $ini = [
                'lottery_code' => $lottery_code,
                'member_id'    => Session::get('member_id'),
                'type_id'      => 2,
                'create_time'  => time(),
            ];

            $model->save($ini);

            Db::name('member')->where('id', Session::get('member_id'))->setDec('integral', 1);

            Db::name('integral_record')->insert(
                [
                    'member_id'   => Session::get('member_id'),
                    'type_id'     => '2',
                    'type'        => '兑换',
                    'integral'    => 1,
                    'title'       => '兑换' . '抽奖码',
                    'create_time' => time()
                ]
            );

            // 提交事务
            Db::commit();

            return ['code' => 200, 'message' => '兑换成功'];
        }catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'message' => '网络繁忙,请重试'];
        }


    }




    /**
     * 判断会员是否已签到
     */
    public function checkSign($id)
    {
        // 判断memberId 是否为空
        if (empty($id)) return "signNo";

        // 筛选条件
        $condtion = [
            'member_id' => $id,
            'sign_time' => date('Y-m-d', time()),
        ];

        // 判断是否签到
        $operation = (new MemberSignModel())->where($condtion)->find();
        if ($operation) {
            return "signIn";
        }
        return "signNo";
    }


    /**
     * 前置方法(误删)
     */
    public function checkLogin()
    {
        if (false === Session::has('member_id')) {
            $this->redirect('shop/Login/index');
        }

    }

}